package registry

import (
	"context"
	"fmt"
	"strings"

	"github.com/containers/common/pkg/retry"
	"github.com/containers/image/v5/transports/alltransports"
	"github.com/containers/image/v5/types"

	"gopkg.openfuyao.cn/bkeadm/utils/log"
)

func (op *Options) Delete() {
	if len(op.Args) != 1 {
		log.Error("only one mirror can be deleted at a time")
		return
	}
	imageName := op.Args[0]
	if !strings.HasPrefix(imageName, "docker://") {
		imageName = fmt.Sprintf("docker://%s", imageName)
	}
	ref, err := alltransports.ParseImageName(imageName)
	if err != nil {
		log.Error(fmt.Sprintf("invalid image name %s: %v", imageName, err))
		return
	}

	destinationCtx, err := newSystemContext()
	if err != nil {
		log.Error(err)
		return
	}
	if op.DestTLSVerify {
		destinationCtx.DockerInsecureSkipTLSVerify = types.NewOptionalBool(true)
		destinationCtx.DockerDaemonInsecureSkipTLSVerify = true
	}

	ctx := context.Background()
	err = retry.IfNecessary(ctx, func() error {
		return ref.DeleteImage(ctx, destinationCtx)
	}, &retry.Options{
		MaxRetry: 0,
		Delay:    0,
	})
	if err != nil {
		log.Error(err.Error())
		return
	}
	return
}
